package com.atguigu.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @Author luoyin
 * @Date 16:54 2022/7/25
 **/
public class JSONUtils {
    /*
     * Java对象转换为json字符串
     * @param: obj
     * @return:java.lang.String
     **/
    public static String object2JsonStr(Object obj) throws JsonProcessingException {
        return new ObjectMapper().writeValueAsString(obj);
    }

    /*
     * 解析json字符串转换为Java对象
     * @param: jsonStr
     * @Param: clazz   对象类型
     * @return:T
     **/
    public static <T> T jsonStr2Object(String jsonStr, Class<T> clazz) throws IOException {
        return new ObjectMapper().readValue(jsonStr, clazz);
    }

    /*
     * 获取请求正文,并转换为Java对象
     * @param: request
     * @Param: clazz  对象类型
     * @return:T
     **/
    public static <T> T request2Object(HttpServletRequest request, Class<T> clazz) throws IOException {

        BufferedReader reader = request.getReader();
        StringBuilder sb = new StringBuilder();
        String len = null;
        while ((len = reader.readLine()) != null) {
            sb.append(len);
        }
        reader.close();
        System.out.println("sb = " + sb);
        return jsonStr2Object(sb.toString(), clazz);

    }

    /*
     * 将Java对象转换为json字符串并响应给浏览器
     * @param: response
     * @Param: t   java对象
     * @return:void
     **/
    public static<T> void object2JsonStrAndresponse(HttpServletResponse response , T t) throws IOException {
        //告诉服务器以utf-8编码字符串,告诉浏览器以utf-8解码字符串
        response.setContentType("application/json;charset=utf-8");
        String jsonStr = object2JsonStr(t);
        response.getWriter().write(jsonStr);
    }
}
